﻿using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

namespace JsonToSql
{
    /// <summary>
    /// Row created from json text format 
    /// </summary>
    public class JsonRow
    {
        private Dictionary<string, JsonCell> cells;
        /// <summary>
        /// All cells for row
        /// </summary>
        public Dictionary<string, JsonCell> Cells
        {
            get
            {
                return cells;
            }
        }
        private JToken token;
        private JsonTable parent;
        /// <summary>
        /// Parent table
        /// </summary>
        public JsonTable Parent
        {
            get
            {
                return parent;
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="token">Token text format of row</param>
        /// <param name="parent">Parent table</param>
        public JsonRow(JToken token, JsonTable parent)
        {
            this.token = token;
            this.parent = parent;
            createCells();
        }
        private void createCells()
        {
            if (token != null)
            {
                cells = (from item in token.Values().ToList()
                         select new JsonCell(item, this)).ToDictionary(x => x.Name, x => x);
            }
        }
        /// <summary>
        /// Indexer of cells
        /// </summary>
        /// <param name="name">Name of column - cell</param>
        /// <returns>Cell object</returns>
        public JsonCell this[string name]
        {
            get
            {
                return Cells[name];
            }
        }
    }
}
